<script setup>
import { ref, reactive, nextTick } from 'vue';
import { sensorById, sensorByIdCtrl } from '@T2/service/api.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute } from 'vue-router';
import { useIuserInfoStore } from '@T2/store/users.ts';

const props = defineProps({
  disabled: {
    type: Boolean,
    default: true,
  }
});

const PLCSetUp = reactive({
  visible: false,
  id: null,
  lastdata_cn: '',
  datatype: '',
  datatype_json_arr: [],
  v: null,
});
const PLCSetRef = ref(null);
const checkPopup = async (editObj, dataIndex) => {
  if (props.disabled) {
    ElMessage.error('您没有控制权限，请联系管理员！');
    return;
  }
  if (editObj.editType === 'number01') {
    let statusT = editObj.data[dataIndex].statusT;
    if (statusT && statusT.rw === '读写') {
      PLCSetUp.visible = true;
      PLCSetUp.id = statusT.id; //注意这个id可能直接绑定的id，也可能是后缀和前缀组合成的变量地址对应的id，详情请看exchange.js
      PLCSetUp.lastdata_cn = statusT.val;
      nextTick(() => {
        PLCSetRef.value.clearValidate();
      });
      await getSensorById(statusT.id);
    }
  } else if (editObj.editType === 'switch01') {
    let writeT = editObj.data[0].writeT, statusT = editObj.data[0].statusT;
    PLCSetUp.id = statusT.id; //注意这个id可能直接绑定的id，也可能是后缀和前缀组合成的变量地址对应的id，详情请看exchange.js
    if (writeT && statusT.val !== '掉线' && statusT.val != undefined) {
      let act = writeT.act;
      if (typeof +act === 'number'){
        PLCSetUp.v = +act;
      } else {
        return;
      }
      ElMessageBox.confirm('确定要切换吗？').then(() => {
        editSensor();
      }).catch(() => {
        ElMessage.info('已取消');
      });
    } else if (writeT){
      ElMessage.warning('数据离线，请检查网关状态');
    }
  }
}
const getSensorById = async (id) => {
  PLCSetUp.v = null;
  PLCSetUp.datatype = '';
  PLCSetUp.datatype_json_arr = [];
  await sensorById({
    method: 'get',
    id: id,
    params: {},
  }).then(res => {
    PLCSetUp.datatype = res.datatype;
    if (res.datatype === '状态型') {
      const json = JSON.parse(res.datatype_json);
      json['0'] && PLCSetUp.datatype_json_arr.push({id: 1, v: 0, name: json['0']});
      json['1'] && PLCSetUp.datatype_json_arr.push({id: 2, v: 1, name: json['1']});
      json['2'] && PLCSetUp.datatype_json_arr.push({id: 3, v: 2, name: json['2']});
      json['3'] && PLCSetUp.datatype_json_arr.push({id: 4, v: 3, name: json['3']});
      json['4'] && PLCSetUp.datatype_json_arr.push({id: 5, v: 4, name: json['4']});
      json['5'] && PLCSetUp.datatype_json_arr.push({id: 6, v: 5, name: json['5']});
    }
  });
}

const PLCSetClick = () => {
  PLCSetRef.value.validate((valid) => {
    if (valid) {
      PLCSetUp.visible = false;
      editSensor();
    }
  });
}
const editSensor = () => {
  PLCSetUp.id && sensorByIdCtrl({
    method: 'post',
    id: PLCSetUp.id,
    data: {
      v: PLCSetUp.v,
    },
  }).then(res => {
    ElMessage.success('发送成功！数据存在一定延迟，请耐心等待');
  });
}

defineExpose({
  checkPopup
});
</script>

<template>
  <div>
    <el-dialog
      class="plc-box"
      v-model="PLCSetUp.visible"
      title="PLC写入"
      width="450px"
    >
      <div class="cur">{{PLCSetUp.datatype === '数值型' ? '当前数值：' : '当前状态：'}}{{PLCSetUp.lastdata_cn}}</div>
      <el-form
        ref="PLCSetRef"
        :model="PLCSetUp"
        label-width="120px"
      >
        <el-form-item
          label="写入数值："
          prop="v"
          :rules="[{required: true, message: '不能为空', trigger: 'blur'},]"
          style="width: 90%;"
          v-if="PLCSetUp.datatype === '数值型'"
        >
          <el-input-number class="inums" placeholder="请输入数值" v-model="PLCSetUp.v"></el-input-number>
        </el-form-item>
        
        <el-form-item
          label="切换状态"
          prop="v"
          style="width: 90%;"
          :rules="[{required: true, message: '不能为空', trigger: 'change'},]"
          v-else-if="PLCSetUp.datatype === '状态型'"
        >
          <el-select v-model="PLCSetUp.v">
            <el-option
              v-for="(item, index) in PLCSetUp.datatype_json_arr"
              :key="item.id"
              :value="item.v"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="PLCSetUp.visible = false">取 消</el-button>
        <el-button type="primary" @click="PLCSetClick()">写 入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.inums {
  width: 100%;
}
.cur {
  font-size: 15px;
  padding-bottom: 10px;
  text-align: center;
  color: #0055ff;
}
</style>
<style scoped>
:deep(.plc-box.el-dialog .el-dialog__footer) {
  text-align: right;
}
</style>
